package com.zichan360.service;

import com.zichan360.domain.CompanyTransform;
import com.zichan360.domain.User;
import com.zichan360.exception.Exception404;
import com.zichan360.exception.message.CompanyException;
import com.zichan360.exception.message.UserException;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 创建用户:杨辽
 * 创建时间: 2018-03-13 19:36
 * 描   述:
 **/
@Service
public class UserService {

    /**
     * 模拟数据库
     */
    private final Map<String, User> data = new ConcurrentHashMap<>();

    public Flux<User> list() {
        return Flux.fromIterable(this.data.values());
    }

    public Flux<User> getById(final Flux<String> ids) {
        return ids.flatMap(id -> Mono.justOrEmpty(this.data.get(id)));
    }

    public Mono<User> getById(final String id) {
        //如果找不到 ID 对应的 User 对象，会返回一个包含了 ResourceNotFoundException 异常通知的 Mono 对象。
        return Mono.justOrEmpty(this.data.get(id)).switchIfEmpty(Mono.error(new Exception404()));
    }

    public Flux<User> createOrUpdate(final Flux<User> users) {
        return users.doOnNext(user -> this.data.put(user.getId(), user));
    }

    public Mono<User> createOrUpdate(final User user) {
        this.data.put(user.getId(), user);
        return Mono.just(user);
    }

    public Mono<User> delete(final String id) {
        return Mono.justOrEmpty(this.data.remove(id));
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public Mono<ServerResponse> getById(ServerRequest request) {
//        return Mono.justOrEmpty(this.data.get(request.pathVariable("id")))
//                .flatMap(user -> ServerResponse.ok().body(Mono.just(user), User.class))
//                .switchIfEmpty(Mono.error(new UserException()));

        return ServerResponse.ok().body(Mono.just(this.data.get(request.pathVariable("id"))), User.class).switchIfEmpty(Mono.error(new UserException()));
    }

    public Mono<ServerResponse> list(ServerRequest request) {
        return ServerResponse.ok().body(Flux.fromStream(data.values().stream()), User.class).switchIfEmpty(Mono.error(new UserException()));
    }

    public Mono<ServerResponse> createOrUpdate(ServerRequest request) {
        User user = request.bodyToMono(User.class).block();
        this.data.put(user.getId(), user);
        return ServerResponse.ok().body(Mono.just(user), User.class);
    }




}